package com.kyzh.core.pager.login

import android.content.Intent
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import androidx.core.content.ContextCompat
import com.bytedance.applog.game.GameReportHelper
import com.gushenge.atools.util.getStatusBarHeight
import com.gushenge.atools.util.setMargins
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.dao.GlobalConsts
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.requests.UserRequest
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.utils.*
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import io.github.armcha.autolink.MODE_URL
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_register.*
import kotlinx.android.synthetic.main.activity_register.cblogin
import kotlinx.android.synthetic.main.activity_register.etAccount
import kotlinx.android.synthetic.main.activity_register.etPassword
import kotlinx.android.synthetic.main.activity_register.ivDel
import kotlinx.android.synthetic.main.activity_register.ivLogo
import kotlinx.android.synthetic.main.activity_register.ivShowpass
import kotlinx.android.synthetic.main.activity_register.tvPact
import kotlinx.android.synthetic.main.activity_register.tvPhoneLogin
import kotlinx.android.synthetic.main.activity_register.tvQQLogin
import kotlinx.android.synthetic.main.activity_register.tvWxLogin
import com.gushenge.core.toast
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.activities.PasswordActivity

/**
 * Created by Administrator on 2017/8/18 0018.
 */

class RegisterActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        initUI()
    }


    var loginbox = false
    private fun initUI() {
        cblogin.isChecked= loginbox
        cblogin.setOnCheckedChangeListener { buttonView, isChecked ->
            loginbox =isChecked
        }
        tvQQLogin.setVisibility(MMKVConsts.qqLogin)
        tvWxLogin.setVisibility(MMKVConsts.wxLogin)
        ivLogo.setMargins(0,
                if (isNotLongScreenDevice()){
                    dip(58)
                }else{
                    dip(88)+getStatusBarHeight()
                },
                0,
                0
        )
        btRegister.setOnClickListener {
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            val name = etAccount.text.toString().trim()
            val password = etPassword.text.toString().trim()
            val password2 = etPassword2.text.toString().trim()
            val code = etCode.text.toString().trim()
            UserRequest.registerByUserName(name,password,password2,code){
                GameReportHelper.onEventRegister("amount",true);

                imLogin()
                LiveEventBus.get<Boolean>("login").post(true)
                finish()
            }
        }
        tvPact.addAutoLinkMode(
                MODE_URL
        )
        tvPact.addUrlTransformations(
                GlobalConsts.REGISTER_PACT to "“${getString(R.string.registerAgreement)}”",
                GlobalConsts.PRIVACY_PACT to "“${getString(R.string.privacyPolicy)}”"
        )
        tvPact.urlModeColor = ContextCompat.getColor(this, R.color.colorPrimary)
        tvPact.text = String.format(getString(R.string.loginPrivacy),GlobalConsts.REGISTER_PACT,GlobalConsts.PRIVACY_PACT)


        tvPact.onAutoLinkClick {
            startActivity<BrowserActivity>(GlobalKeys.TITLE to it.transformedText.substring(1,it.transformedText.length-1), GlobalKeys.LINK to it.originalText)
        }
        tvLogin.setOnClickListener{
            startActivity<LoginActivity>()
            finish()
        }
        tvPhoneLogin.setOnClickListener{
            startActivity<PhoneLoginActivity>()
            finish()
        }
        ivShowpass.setOnClickListener{
            showPass()
        }
        ivShowpass2.setOnClickListener{
            showPass2()
        }
        ivDel.setOnClickListener {
            etAccount.setText("")
        }
        tvQQLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.QQ, authListener)
        }
        tvWxLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener)
        }
    }
    /*tvFindPassword -> startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.RETRIEVE_PASSWORD)*/
    //Im登录
    private fun imLogin(){
//        if(MMKVConsts.imOpen) {
//            LiveRequest.geiLiveUserUid {
//                this?.apply {
//                    TUILogin.login(live_uid, live_sign, object : V2TIMCallback {
//                        override fun onSuccess() {
//                            Log.e(TUIUtils.TAG, "onSuccess")
//                        }
//
//                        override fun onError(p0: Int, p1: String?) {
//                            Log.e(TUIUtils.TAG, "onError: $p0  $p1")
//                        }
//                    })
//                }
//            }
//        }
    }

    private fun showPass() {
        if (etPassword.transformationMethod != HideReturnsTransformationMethod.getInstance()) {
            etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_showpassword))
        } else {
            etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_hidepassword))
        }
    }

    private fun showPass2() {
        if (etPassword2.transformationMethod != HideReturnsTransformationMethod.getInstance()) {
            etPassword2.transformationMethod = HideReturnsTransformationMethod.getInstance()
            ivShowpass2.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_showpassword))
        } else {
            etPassword2.transformationMethod = PasswordTransformationMethod.getInstance()
            ivShowpass2.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_login_hidepassword))
        }
    }
    // 设置密码  type ==1  QQ   2 wx
    fun setPassword(token: String? ,type :Int){
        PasswordActivity.start(this, token, type)
    }
    var authListener: UMAuthListener = object : UMAuthListener {

        override fun onStart(platform: SHARE_MEDIA) {}
        override fun onComplete(platform: SHARE_MEDIA, action: Int, data: Map<String, String>) {
            if (platform == SHARE_MEDIA.QQ) {
                UserImpl.checkReg(data["accessToken"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["accessToken"] ?: "", "1",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        setPassword(data["accessToken"] ?: "",1)
                    }
                }
            } else {
                UserImpl.checkReg(data["uid"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["uid"] ?: "", "2",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        setPassword(data["uid"] ?: "",2)
                    }
                }
            }
        }
        override fun onError(platform: SHARE_MEDIA, action: Int, t: Throwable) {}
        override fun onCancel(platform: SHARE_MEDIA, action: Int) {
            getString(R.string.cancelLogin).toast()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 1000){
            if(resultCode == RESULT_OK){
                finish()
            }
        }else{

            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        }

    }

}
